<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="设备ID">
              <el-input v-model="searchForm.deviceId" placeholder="请输入设备ID" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="设备名称">
              <el-input v-model="searchForm.deviceName" placeholder="请输入设备名称" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="设备型号">
              <el-input v-model="searchForm.deviceModel" placeholder="请输入设备型号" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="IP地址">
              <el-input v-model="searchForm.ipAddress" placeholder="请输入IP地址" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="设备状态">
              <el-select v-model="searchForm.deviceStatus" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="在线" :value="1" />
                <el-option label="离线" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div>
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon class="el-icon--left">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon class="el-icon--left">
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon online">
              <el-icon>
                <VideoCamera />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.onlineCount }}</div>
              <div class="stat-label">在线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon offline">
              <el-icon>
                <VideoCamera />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.offlineCount }}</div>
              <div class="stat-label">离线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon>
                <Monitor />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalCount }}</div>
              <div class="stat-label">设备总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bound">
              <el-icon>
                <Connection />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.boundCount }}</div>
              <div class="stat-label">已关联站点</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <el-button type="success" @click="handleSyncDevices" :loading="syncing">
        <el-icon class="el-icon--left">
          <Refresh />
        </el-icon>
        同步设备
      </el-button>
      <el-button @click="refreshData">
        <el-icon class="el-icon--left">
          <Refresh />
        </el-icon>
        刷新
      </el-button>
      <el-table :data="tableData" v-loading="loading" border style="width: 100%" class="mt-2"
        @selection-change="handleSelectionChange" @row-contextmenu="handleTableContextMenu">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="deviceId" label="设备ID" align="center" width="120" />

        <el-table-column prop="deviceName" label="设备名称" align="center" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="device-name-cell">
              <el-icon class="device-icon">
                <VideoCamera />
              </el-icon>
              <span class="name-text">{{ row.deviceName || '-' }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="deviceModel" label="设备型号" align="center" width="150" show-overflow-tooltip />

        <el-table-column prop="ipAddress" label="IP地址" align="center" width="130" />

        <el-table-column prop="deviceStatus" label="设备状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getDeviceStatusTag(row.deviceStatus)" size="small" effect="light">
              {{ getDeviceStatusText(row.deviceStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="firmwareVer" label="固件版本" align="center" width="100" />

        <el-table-column prop="siteInfo" label="关联站点" align="center" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.siteId" type="success" size="small">{{ getName(siteOptions, row.siteId, 'stationId',
              'stationName' ) }}</el-tag>
            <el-tag v-else type="info" size="small">{{ '未关联' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center" width="160">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="updateTime" label="更新时间" align="center" width="160">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.updateTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-button-group">
              <el-button type="primary" link size="small" @click="handleViewDetail(row)">
                详情
              </el-button>
              <el-button type="success" link size="small" @click="handleBindSite(row)">
                关联站点
              </el-button>
              <el-button type="warning" link size="small" @click="handleViewStreams(row)">
                码流配置
              </el-button>
              <el-button type="info" link size="small" @click="handleViewHistory(row)">
                历史回放
              </el-button>
              <el-button type="danger" link size="small" @click="handleUnbindSite(row)" v-if="row.siteId">
                解除关联
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tableData.length > 0">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <div v-if="tableData.length === 0" class="empty-table">
        <el-empty description="暂无设备数据" :image-size="80" />
      </div>
    </el-card>

    <!-- 设备详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="detailTitle" width="800px" :before-close="handleCloseDetailDialog">
      <div v-if="currentDetail" class="device-detail">
        <el-tabs v-model="activeDetailTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="设备ID">{{ currentDetail.deviceId || '-' }}</el-descriptions-item>
              <el-descriptions-item label="设备名称">{{ currentDetail.deviceName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="设备型号">{{ currentDetail.deviceModel || '-' }}</el-descriptions-item>
              <el-descriptions-item label="IP地址">{{ currentDetail.ipAddress || '-' }}</el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <el-tag :type="getDeviceStatusTag(currentDetail.deviceStatus)" size="small">
                  {{ getDeviceStatusText(currentDetail.deviceStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="固件版本">{{ currentDetail.firmwareVer || '-' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) || '-'
              }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updateTime) || '-'
              }}</el-descriptions-item>
              <el-descriptions-item label="创建者">{{ currentDetail.createBy || '-' }}</el-descriptions-item>
              <el-descriptions-item label="备注">{{ currentDetail.remark || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 站点关联信息 -->
          <el-tab-pane label="站点关联" name="site">
            <div v-if="currentDetail.siteId" class="site-info">
              <el-descriptions title="关联站点信息" :column="1" border>
                <el-descriptions-item label="站点ID">{{ currentDetail.siteId || '-' }}</el-descriptions-item>
                <el-descriptions-item label="站点名称">{{ currentDetail.deviceName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="站点层级">
                  <el-tag :type="getSiteLevelTag(currentDetail.stationLevel)" size="small">
                    {{ getSiteLevelText(currentDetail.stationLevel) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="站点地址">{{ currentDetail.stationAddr || '-' }}</el-descriptions-item>
                <el-descriptions-item label="区域ID">{{ currentDetail.areaId || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-else class="no-site-info">
              <el-empty description="该设备未关联任何站点" :image-size="100" />
              <div class="bind-action">
                <el-button type="primary" @click="handleBindSite(currentDetail)">
                  立即关联站点
                </el-button>
              </div>
            </div>
          </el-tab-pane>

          <!-- 码流信息 -->
          <el-tab-pane label="码流配置" name="streams">
            <div class="streams-section">
              <div class="section-header">
                <h4>可用码流列表</h4>
                <el-button type="primary" size="small" @click="loadStreams(currentDetail.deviceId)">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  刷新码流
                </el-button>
              </div>

              <div v-if="streamList.length > 0" class="streams-list">
                <el-table :data="streamList" size="small">
                  <el-table-column prop="label" label="清晰度" width="100" />
                  <el-table-column prop="protocol" label="协议" width="100">
                    <template #default="{ row }">
                      {{ getProtocolText(row.protocol) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="streamKey" label="流密钥" show-overflow-tooltip />
                  <el-table-column prop="isDefault" label="默认流" width="80">
                    <template #default="{ row }">
                      <el-tag v-if="row.isDefault === 1" type="success" size="small">
                        是
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="authMode" label="鉴权方式" width="100">
                    <template #default="{ row }">
                      {{ getAuthModeText(row.authMode) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button type="primary" link size="small" @click="handlePlayStream(row)">
                        播放
                      </el-button>
                      <el-button type="info" link size="small" @click="handleCopyStreamUrl(row)">
                        复制URL
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-else class="no-streams">
                <el-empty description="暂无码流信息" :image-size="80" />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <el-button @click="handleCloseDetailDialog">关闭</el-button>
        <el-button type="primary" @click="handleBindSite(currentDetail)" v-if="currentDetail">
          关联站点
        </el-button>
        <el-button type="success" @click="handleViewStreams(currentDetail)" v-if="currentDetail">
          查看码流
        </el-button>
      </template>
    </el-dialog>

    <!-- 关联站点对话框 -->
    <el-dialog v-model="bindDialogVisible" :title="bindDialogTitle" width="600px" :before-close="handleCloseBindDialog">
      <el-form ref="bindFormRef" :model="bindForm" :rules="bindFormRules" label-width="100px">
        <el-form-item label="设备信息">
          <div class="device-info">
            <span class="device-name">{{ currentDevice?.deviceName }}</span>
            <span class="device-id">(ID: {{ currentDevice?.deviceId }})</span>
          </div>
        </el-form-item>

        <el-form-item label="选择站点" prop="siteId">
          <el-select v-model="bindForm.siteId" placeholder="请选择站点" filterable style="width: 100%"
            @change="handleSiteChange">
            <el-option v-for="site in siteOptions" :key="site.stationId"
              :label="`${site.stationName} (${site.stationAddr})`" :value="site.stationId">
              <div class="site-option">
                <span class="site-name">{{ site.stationName }}</span>
                <span class="site-level">
                  <el-tag :type="getSiteLevelTag(site.stationLevel)" size="small">
                    {{ getSiteLevelText(site.stationLevel) }}
                  </el-tag>
                </span>
                <span class="site-addr">{{ site.stationAddr }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联备注" prop="relRemark">
          <el-input v-model="bindForm.relRemark" type="textarea" :rows="3" placeholder="请输入关联备注信息" maxlength="200"
            show-word-limit />
        </el-form-item>

        <!-- <el-form-item label="创建用户" prop="createUser">
          <el-input v-model="bindForm.createUser" placeholder="请输入创建用户" style="width: 100%" />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <el-button @click="handleCloseBindDialog">取消</el-button>
        <el-button type="primary" @click="handleBindSubmit" :loading="binding">
          确认关联
        </el-button>
      </template>
    </el-dialog>

    <!-- 码流配置对话框 -->
    <el-dialog v-model="streamDialogVisible" :title="streamDialogTitle" width="900px"
      :before-close="handleCloseStreamDialog">
      <div v-if="currentDevice" class="stream-config">
        <div class="stream-filter">
          <el-form :inline="true" :model="streamFilter">
            <el-form-item label="清晰度">
              <el-select v-model="streamFilter.label" placeholder="选择清晰度" clearable @change="handleStreamFilterChange"
                style="width: 300px;">
                <el-option v-for="quality in qualityOptions" :key="quality.dictValue" :label="quality.dictLabel"
                  :value="quality.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item label="协议">
              <el-select v-model="streamFilter.protocol" placeholder="选择协议" clearable @change="handleStreamFilterChange"
                style="width: 300px;">
                <el-option label="HLS" :value="1" />
                <el-option label="FLV" :value="2" />
                <el-option label="RTC" :value="3" />
                <el-option label="RTSP" :value="4" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="streams-table">
          <el-table :data="filteredStreams" v-loading="streamLoading">
            <el-table-column prop="label" label="清晰度" width="100" />
            <el-table-column prop="protocol" label="协议" width="100">
              <template #default="{ row }">
                {{ getProtocolText(row.protocol) }}
              </template>
            </el-table-column>
            <el-table-column prop="streamKey" label="流密钥" show-overflow-tooltip />
            <el-table-column prop="isDefault" label="默认流" width="80">
              <template #default="{ row }">
                <el-tag v-if="row.isDefault === 1" type="success" size="small">
                  是
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="authMode" label="鉴权方式" width="100">
              <template #default="{ row }">
                {{ getAuthModeText(row.authMode) }}
              </template>
            </el-table-column>
            <el-table-column prop="urlTemplate" label="URL模板" show-overflow-tooltip />
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handlePlayStream(row)">
                  播放
                </el-button>
                <el-button type="info" link size="small" @click="handleCopyStreamUrl(row)">
                  复制
                </el-button>
                <!-- <el-button type="success" link size="small" @click="handleSetDefault(row)">
                  设默认
                </el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="stream-preview" v-if="selectedStream">
          <h4>流预览</h4>
          <div class="preview-content">
            <div class="stream-url">
              <span class="url-label">流地址:</span>
              <span class="url-value">{{ getStreamUrl(selectedStream) }}</span>
              <el-button type="text" @click="handleCopyUrl(getStreamUrl(selectedStream))">
                <el-icon>
                  <DocumentCopy />
                </el-icon>
              </el-button>
            </div>
              <LivePlayer :src="getStreamUrl(selectedStream)" protocol="mp4" :autoplay="true" :controls="true"/>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="handleCloseStreamDialog">关闭</el-button>
        <el-button type="primary" @click="handleRefreshStreams">
          刷新码流
        </el-button>
      </template>
    </el-dialog>

    <!-- 历史回放对话框 -->
    <el-dialog v-model="historyDialogVisible" title="历史视频回放" width="1000px" :before-close="handleCloseHistoryDialog">
      <div v-if="currentDevice" class="history-playback">
        <div class="history-filter">
          <el-form :inline="true" :model="historyFilter">
            <el-form-item label="开始时间">
              <el-date-picker v-model="historyFilter.startTime" type="datetime" placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker v-model="historyFilter.endTime" type="datetime" placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearchHistory">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="history-list">
          <el-table :data="historyVideos" v-loading="historyLoading">
            <el-table-column prop="videoId" label="视频ID" width="120" />
            <el-table-column prop="startTime" label="开始时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="fileSize" label="文件大小" width="100">
              <template #default="{ row }">
                {{ formatFileSize(row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column prop="videoFormat" label="格式" width="80" />
            <el-table-column prop="storageStatus" label="存储状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStorageStatusTag(row.storageStatus)" size="small">
                  {{ getStorageStatusText(row.storageStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="handlePlayHistory(row)">
                  播放
                </el-button>
                <el-button type="info" link size="small" @click="handleDownloadHistory(row)">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="handleCloseHistoryDialog">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 右键菜单 -->
    <div v-if="contextMenuVisible" class="context-menu" :style="contextMenuStyle">
      <div class="menu-item" @click="handleContextMenuAction('view')">
        <el-icon>
          <View />
        </el-icon>
        查看详情
      </div>
      <div class="menu-item" @click="handleContextMenuAction('bind')">
        <el-icon>
          <Connection />
        </el-icon>
        关联站点
      </div>
      <div class="menu-item" @click="handleContextMenuAction('streams')">
        <el-icon>
          <VideoPlay />
        </el-icon>
        码流配置
      </div>
      <div class="menu-item" @click="handleContextMenuAction('history')">
        <el-icon>
          <Clock />
        </el-icon>
        历史回放
      </div>
      <div class="menu-item danger" @click="handleContextMenuAction('unbind')" v-if="contextMenuRow?.siteId">
        <el-icon>
          <Unlock />
        </el-icon>
        解除关联
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs';
import LivePlayer from '@/components/LivePlayer';

// 图标引入
import {
  Search,
  Refresh,
  Plus,
  Download,
  Connection,
  VideoCamera,
  Monitor,
  View,
  Timer,
  DocumentCopy,
  VideoPlay,
  Clock,
  Unlock
} from '@element-plus/icons-vue'

// API引入
import {
  syncVideoDevices,
  getVideoDeviceList,
  getVideoDeviceDetail,
  getSiteList,
  bindDeviceToSite,
  getQualityList,
  getStreamList,
  getHistoryVideoList,
  unbindDevice,
  getSiteInfo
} from '@/api/park/video'

// 响应式数据
const searchForm = reactive({
  deviceId: '',
  deviceName: '',
  deviceModel: '',
  ipAddress: '',
  deviceStatus: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const activeDetailTab = ref('basic');

const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)
const syncing = ref(false)
const binding = ref(false)

// 统计信息
const stats = reactive({
  onlineCount: 0,
  offlineCount: 0,
  totalCount: 0,
  boundCount: 0
})

// 对话框控制
const detailDialogVisible = ref(false)
const bindDialogVisible = ref(false)
const streamDialogVisible = ref(false)
const historyDialogVisible = ref(false)

// 当前操作设备
const currentDevice = ref(null)
const currentDetail = ref(null)
const selectedStream = ref(null)

// 站点选项
const siteOptions = ref([])
const qualityOptions = ref([])

// 码流数据
const streamList = ref([])
const streamLoading = ref(false)
const historyVideos = ref([])
const historyLoading = ref(false)

// 表单数据
const bindForm = reactive({
  siteId: '',
  relRemark: '',
  createUser: ''
})

const streamFilter = reactive({
  label: '',
  protocol: ''
})

const historyFilter = reactive({
  startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
  endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

// 表单验证规则
const bindFormRules = {
  siteId: [
    { required: true, message: '请选择站点', trigger: 'change' }
  ],
  relRemark: [
    { required: true, message: '请输入关联备注', trigger: 'blur' }
  ],
  createUser: [
    { required: true, message: '请输入创建用户', trigger: 'blur' }
  ]
}

// 右键菜单
const contextMenuVisible = ref(false)
const contextMenuStyle = reactive({
  left: '0px',
  top: '0px'
})
const contextMenuRow = ref(null)

// 自动刷新
const autoRefreshInterval = ref(null)

// 计算属性
const detailTitle = computed(() => {
  return currentDetail.value ? `${currentDetail.value.deviceName} - 设备详情` : '设备详情'
})

const bindDialogTitle = computed(() => {
  return currentDevice.value ? `关联站点 - ${currentDevice.value.deviceName}` : '关联站点'
})

const streamDialogTitle = computed(() => {
  return currentDevice.value ? `码流配置 - ${currentDevice.value.deviceName}` : '码流配置'
})

const filteredStreams = computed(() => {
  let streams = streamList.value

  if (streamFilter.label) {
    streams = streams.filter(stream => stream.label === streamFilter.label)
  }

  if (streamFilter.protocol) {
    streams = streams.filter(stream => stream.protocol === streamFilter.protocol)
  }

  return streams
})

// 初始化数据
onMounted(() => {
  initData()
  startAutoRefresh()
  setupKeyboardShortcuts()
})

onBeforeUnmount(() => {
  stopAutoRefresh()
})

const initData = async () => {
  try {
    await Promise.all([
      loadDeviceList(),
      loadSiteList(),
      loadQualityList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 加载设备列表
const loadDeviceList = async () => {
  try {
    loading.value = true

    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getVideoDeviceList(params)

    tableData.value = res.rows || []
    pagination.total = res.total || 0
    updateStats(tableData.value)
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 更新统计信息
const updateStats = (devices) => {
  stats.totalCount = devices.length
  stats.onlineCount = devices.filter(d => d.deviceStatus === 1).length
  stats.offlineCount = devices.filter(d => d.deviceStatus === 0).length
  stats.boundCount = devices.filter(d => d.siteId).length
}

// 加载站点列表
const loadSiteList = async () => {
  try {
    const res = await getSiteList()
    siteOptions.value = res.data || []
  } catch (error) {
    console.error('加载站点列表失败:', error)
  }
}

// 加载清晰度列表
const loadQualityList = async () => {
  try {
    const res = await getQualityList()
    qualityOptions.value = res.data || []
  } catch (error) {
    console.error('加载清晰度列表失败:', error)
  }
}

// 同步设备
const handleSyncDevices = async () => {
  try {
    syncing.value = true
    const res = await syncVideoDevices()
    ElMessage.success('设备同步成功')
    loadDeviceList()
  } catch (error) {
    console.error('设备同步失败:', error)
    ElMessage.error('设备同步失败')
  } finally {
    syncing.value = false
  }
}

// 新增设备
const handleAddDevice = () => {
  ElMessage.info('新增设备功能开发中')
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const res = await getVideoDeviceDetail(row.deviceId)
    const device = await getSiteInfo(row.siteId);
    
    currentDetail.value = { ...res.data, ...device.data };
    detailDialogVisible.value = true

    loadStreams(currentDetail.value.deviceId);
  } catch (error) {
    console.error('获取设备详情失败:', error)
    ElMessage.error('获取设备详情失败')
  }
}

// 关联站点
const handleBindSite = (row) => {
  currentDevice.value = row
  bindForm.siteId = ''
  bindForm.relRemark = ''
  bindForm.createUser = 'admin' // 默认用户
  bindDialogVisible.value = true
}

// 查看码流
const handleViewStreams = async (row) => {
  currentDevice.value = row
  streamDialogVisible.value = true
  await loadStreams(row.deviceId)
}

// 查看历史回放
const handleViewHistory = async (row) => {
  currentDevice.value = row
  historyDialogVisible.value = true
  await handleSearchHistory()
}

// 加载码流列表
const loadStreams = async (deviceId) => {
  try {
    streamLoading.value = true
    const res = await getStreamList({ cameraId: deviceId })
    streamList.value = res.data || []
    if (streamList.value.length > 0) {
      selectedStream.value = streamList.value[0]
    }
  } catch (error) {
    console.error('获取码流列表失败:', error)
    ElMessage.error('获取码流列表失败')
  } finally {
    streamLoading.value = false
  }
}

// 搜索历史视频
const handleSearchHistory = async () => {
  try {
    historyLoading.value = true
    const params = {
      cameraId: currentDevice.value.deviceId,
      startTime: historyFilter.startTime,
      endTime: historyFilter.endTime
    }

    const res = await getHistoryVideoList(params)
    historyVideos.value = res.data || []
  } catch (error) {
    console.error('查询历史视频失败:', error)
    ElMessage.error('查询历史视频失败')
  } finally {
    historyLoading.value = false
  }
}

// 批量关联站点
const handleBatchBind = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要关联站点的设备')
    return
  }
  ElMessage.info(`批量关联 ${selectedRows.value.length} 个设备到站点`)
}

// 导出数据
const handleExportData = async () => {
  try {
    loading.value = true
    // 模拟导出过程
    setTimeout(() => {
      ElMessage.success('数据导出成功')
      loading.value = false
    }, 2000)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
    loading.value = false
  }
}

// 解除站点关联
const handleUnbindSite = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除设备 "${row.deviceName}" 的站点关联吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await unbindDevice(row.deviceId);
    ElMessage.success('站点关联已解除')
    loadDeviceList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除关联失败:', error)
      ElMessage.error('解除关联失败')
    }
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  loadDeviceList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    deviceId: '',
    deviceName: '',
    deviceModel: '',
    ipAddress: '',
    deviceStatus: ''
  })
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadDeviceList()
  ElMessage.success('数据已刷新')
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadDeviceList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadDeviceList()
}

// 关闭对话框
const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false
  currentDetail.value = null
}

const handleCloseBindDialog = () => {
  bindDialogVisible.value = false
  resetBindForm()
}

const handleCloseStreamDialog = () => {
  streamDialogVisible.value = false
  resetStreamFilter()
}

const handleCloseHistoryDialog = () => {
  historyDialogVisible.value = false
  resetHistoryFilter()
}

// 重置表单
const resetBindForm = () => {
  Object.assign(bindForm, {
    siteId: '',
    relRemark: '',
    createUser: ''
  })
}

const resetStreamFilter = () => {
  Object.assign(streamFilter, {
    label: '',
    protocol: ''
  })
}

const resetHistoryFilter = () => {
  Object.assign(historyFilter, {
    startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  })
}

// 站点选择变化
const handleSiteChange = (siteId) => {
  const selectedSite = siteOptions.value.find(site => site.stationId === siteId)
  if (selectedSite) {
    bindForm.relRemark = `关联到站点: ${selectedSite.stationName}`
  }
}

// 码流筛选变化
const handleStreamFilterChange = () => {
  // 自动处理筛选
}

// 提交绑定表单
const handleBindSubmit = async () => {
  try {
    binding.value = true

    const bindData = {
      deviceId: currentDevice.value.deviceId,
      siteId: bindForm.siteId,
      relRemark: bindForm.relRemark,
      createUser: bindForm.createUser || 'admin'
    }

    const res = await bindDeviceToSite(bindData)
    ElMessage.success('站点关联成功')
    bindDialogVisible.value = false
    loadDeviceList()
  } catch (error) {
    console.error('站点关联失败:', error)
    ElMessage.error('站点关联失败')
  } finally {
    binding.value = false
  }
}

// 播放码流
const handlePlayStream = (stream) => {
  const streamUrl = getStreamUrl(stream)
  ElMessage.info(`播放码流: ${streamUrl}`)
}

// 复制码流URL
const handleCopyStreamUrl = async (stream) => {
  const streamUrl = getStreamUrl(stream)
  try {
    await navigator.clipboard.writeText(streamUrl)
    ElMessage.success('码流URL已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 设置默认码流
const handleSetDefault = async (stream) => {
  try {
    ElMessage.info(`设置码流 ${stream.label} 为默认流`)
  } catch (error) {
    console.error('设置默认流失败:', error)
    ElMessage.error('设置默认流失败')
  }
}

// 刷新码流
const handleRefreshStreams = async () => {
  if (currentDevice.value) {
    await loadStreams(currentDevice.value.deviceId)
    ElMessage.success('码流列表已刷新')
  }
}

// 播放历史视频
const handlePlayHistory = (video) => {
  ElMessage.info(`播放历史视频: ${video.videoId}`)
}

// 下载历史视频
const handleDownloadHistory = async (video) => {
  try {
    ElMessage.info(`下载历史视频: ${video.videoId}`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 复制URL
const handleCopyUrl = async (url) => {
  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('URL已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 右键菜单处理
const handleTableContextMenu = (event, row) => {
  event.preventDefault()
  contextMenuRow.value = row

  contextMenuStyle.left = event.clientX + 'px'
  contextMenuStyle.top = event.clientY + 'px'
  contextMenuVisible.value = true

  // 点击其他地方关闭菜单
  const closeMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', closeMenu)
  }

  setTimeout(() => {
    document.addEventListener('click', closeMenu)
  }, 100)
}

const handleContextMenuAction = (action) => {
  if (!contextMenuRow.value) return

  switch (action) {
    case 'view':
      handleViewDetail(contextMenuRow.value)
      break
    case 'bind':
      handleBindSite(contextMenuRow.value)
      break
    case 'streams':
      handleViewStreams(contextMenuRow.value)
      break
    case 'history':
      handleViewHistory(contextMenuRow.value)
      break
    case 'unbind':
      handleUnbindSite(contextMenuRow.value)
      break
  }

  contextMenuVisible.value = false
}

// 自动刷新控制
const startAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value)
  }
  autoRefreshInterval.value = setInterval(() => {
    loadDeviceList()
  }, 30000) // 每30秒刷新一次
}

const stopAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value)
    autoRefreshInterval.value = null
  }
}

const toggleAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    stopAutoRefresh()
    ElMessage.info('已停止自动刷新')
  } else {
    startAutoRefresh()
    ElMessage.success('已开启自动刷新')
  }
}

// 键盘快捷键
const setupKeyboardShortcuts = () => {
  const handleKeyDown = (event) => {
    // Ctrl + F 聚焦搜索
    if (event.ctrlKey && event.key === 'f') {
      event.preventDefault()
      // 这里可以聚焦到搜索输入框
    }
    // F5 刷新
    if (event.key === 'F5') {
      event.preventDefault()
      refreshData()
    }
  }

  window.addEventListener('keydown', handleKeyDown)
}

// 工具函数
const getDeviceStatusTag = (status) => {
  return status === 1 ? 'success' : 'danger'
}

const getDeviceStatusText = (status) => {
  return status === 1 ? '在线' : '离线'
}

const getSiteLevelTag = (level) => {
  const levels = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return levels[level] || 'info'
}

const getSiteLevelText = (level) => {
  const levels = {
    1: '城市级',
    2: '区级',
    3: '站点级',
    4: '设备级'
  }
  return levels[level] || level || '-'
}

const getProtocolText = (protocol) => {
  const protocols = {
    1: 'HLS',
    2: 'FLV',
    3: 'RTC',
    4: 'RTSP'
  }
  return protocols[protocol] || '未知'
}

const getAuthModeText = (mode) => {
  const modes = {
    0: '无',
    1: 'Basic',
    2: 'Token',
    3: 'GB28181'
  }
  return modes[mode] || '未知'
}

const getStorageStatusTag = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return statusMap[status] || 'info'
}

const getStorageStatusText = (status) => {
  const statusMap = {
    0: '待存储',
    1: '已存储',
    2: '已删除'
  }
  return statusMap[status] || status || '-'
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTimeString
  }
}

const formatFileSize = (bytes) => {
  if (!bytes) return '-'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

const getStreamUrl = (stream) => {
  if (stream.urlTemplate) {
    return stream.urlTemplate.replace('{STREAM_KEY}', stream.streamKey)
  }
  return stream.streamKey
}

// 组件配置
defineOptions({
  name: 'VideoDeviceManagement'
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  .el-row {
    margin-bottom: 0;
  }
}

.form-actions {
  padding-top: 29px;
  text-align: center;
}

.action-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    gap: 15px;

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;

      &.online {
        background: #67c23a;
      }

      &.offline {
        background: #f56c6c;
      }

      &.total {
        background: #409eff;
      }

      &.bound {
        background: #e6a23c;
      }
    }

    .stat-info {
      flex: 1;

      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-top: 4px;
      }
    }
  }
}

.table-card {
  margin-bottom: 20px;
}

.device-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .device-icon {
    color: #409eff;
  }

  .name-text {
    font-weight: 500;
  }
}

.action-button-group {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-table {
  padding: 40px 0;
  text-align: center;
}

.device-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.site-option {
  display: flex;
  align-items: center;
  gap: 8px;

  .site-name {
    font-weight: 500;
  }

  .site-addr {
    color: #909399;
    font-size: 12px;
  }
}

.streams-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h4 {
      margin: 0;
      color: #303133;
    }
  }
}

.stream-config {
  .stream-filter {
    margin-bottom: 16px;
  }

  .stream-preview {
    margin-top: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .stream-url {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;

      .url-label {
        font-weight: 500;
        color: #606266;
      }

      .url-value {
        flex: 1;
        font-family: monospace;
        background: #fff;
        padding: 4px 8px;
        border-radius: 2px;
        border: 1px solid #dcdfe6;
      }
    }

    .preview-player {
      height: 200px;
      background: #000;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;

      .player-placeholder {
        text-align: center;

        .el-icon {
          font-size: 48px;
          margin-bottom: 8px;
        }

        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }
  }
}

.history-playback {
  max-height: 70vh;
  overflow-y: auto;
}

.history-filter {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;

  .menu-item {
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 8px;

    &:hover {
      background: #f5f7fa;
    }

    &.danger {
      color: #f56c6c;
    }
  }
}

.no-site-info {
  text-align: center;
  padding: 40px 0;

  .bind-action {
    margin-top: 20px;
  }
}

.no-streams {
  text-align: center;
  padding: 40px 0;
}

@media (max-width: 768px) {
  .search-form .el-col {
    margin-bottom: 15px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .stats-row .el-col {
    margin-bottom: 15px;
  }

  .action-button-group {
    flex-direction: column;
    align-items: stretch;
  }
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
    text-align: center;
  }

  th {
    text-align: center;
  }
}

:deep(.el-descriptions) {
  margin-bottom: 16px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-card) {
  margin-bottom: 20px;
}

:deep(.el-card):last-child {
  margin-bottom: 0;
}
</style>